package org.luceneEngine;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.log4j.Logger;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.util.Version;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
//import org.apache.poi.xwpf.
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

/*
 * Lucene Handler for .doc and .docx
 * I'm not actually sure if POI can handle .docx files or not, so this will require testing
 * Otherwise we need to change some stuff
 */
public class LuceneDocHandler extends GenericLuceneDocumentHandler implements LuceneHandler {

	public LuceneDocHandler(String indexDir) throws IOException {
		super(indexDir);
	}

	private static Logger logger = Logger.getLogger(LuceneDocHandler.class.getName());
	
	@Override
	public void writeContents(String fileName, String ensureNotInIndexSearchTerm) {
		try {
			
			logger.debug("Trying to use " + ensureNotInIndexSearchTerm + " as the search term");
			cfg = new IndexWriterConfig(Version.LUCENE_36, analyzer);
			
			if (notInIndex(ensureNotInIndexSearchTerm)) {
				
				logger.debug("Trying to get the text from file: " + fileName);
				String fileText = getTextFromDocument(fileName);
				//Write this into the lucene index
				indexWriter = new IndexWriter(dir, cfg);
				Document doc = new Document();
				logger.debug("Writing " + ensureNotInIndexSearchTerm + " as title");
				doc.add(new Field("title", ensureNotInIndexSearchTerm,
						Field.Store.YES, Field.Index.NOT_ANALYZED));
				doc.add(new Field("content", fileText, Field.Store.YES,
						Field.Index.ANALYZED));
				//If the last character is an 'x', then it is a docx, so strip off the last 5 chars
				if (fileName.charAt(fileName.length() - 1) == 'x') {
					doc.add(new Field("tags", fileName.substring(0,
							fileName.length() - 5), Field.Store.YES,
							Field.Index.ANALYZED));
				}
				//Otherwise its a doc
				else {
					doc.add(new Field("tags", fileName.substring(0,
							fileName.length() - 4), Field.Store.YES,
							Field.Index.ANALYZED));
				}
				indexWriter.addDocument(doc);
				logger.info("Added " + fileName + " to the index");
				indexWriter.close();
			}
		} catch(IOException e){
			logger.warn("Could not get the text from file");
		} 
		
	}
 
	//Reads the text from the .doc file - need to test if this works for docx
	//Returns a single string containing all of the text in the file
	private String getTextFromDocument(String fileName)
			throws FileNotFoundException, IOException {
		File f = new File(fileName);
		FileInputStream in = new FileInputStream(f);
		
		//If the file is a docx
		if(fileName.charAt(fileName.length()-1) == 'x'){
			XWPFDocument doc = new XWPFDocument(in);
			XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
			return extractor.getText();
		}
		
		//Otherwise, if the file is a doc
		else {
			HWPFDocument doc = new HWPFDocument(in);
		 
			WordExtractor extractor = new WordExtractor(doc);
			String fileData[] = extractor.getParagraphText();
			logger.debug("First line of file: " + fileData[0]);
			String finalText = "";
			for(String line : fileData){
				finalText += line + "\n";
			}
			finalText = finalText.substring(0, finalText.length()-1);
			return finalText;
		}
	}

}
